/**
 * request 封装
 */
(function (T, adbox) {
    var request = adbox.request = {};


    /**
     * 常量状态定义
     * @type {Number}
     */
    request.SUCCESS = 0;
    request.SYSTEM_ERROR = 1;
    request.BUSINESS_ERROR = 2;
    request.NO_AUTH = 126;
    request.NO_LOGIN = 127;

    /**
     * 未知错误，404，500 等，无返回情况
     * @return {[type]} [description]
     */
    function unknowError() {
        alert('unknow error!');
    }

    /**
     *  state == 200情况下,返回定义好的状态码对应的处理方法
     */
    /**
     * 业务错误
     * @param  {Function} callback [description]
     * @param  {[type]}   info     [description]
     * @return {[type]}            [description]
     */
    function businessError(callback, info, obj) {
        alert('business error');
        callback(info, obj);
    }
    /**
     * 系统错误
     * @param  {Function} callback [description]
     * @param  {[type]}   info     [description]
     * @return {[type]}            [description]
     */
    function systemError(info) {
        //@todo
        alert('system error!');
    }

    function gotoIndex() {
        alert('goto index');
    }

    function gotoLogin() {
        alert('goto login');
    }

    /**
     * 有返回请求事件回调包装
     */
    function getProcessHandler(onsuccess, onerror) {
        onsuccess = onsuccess || T.fn.blank;
        onerror = onerror || T.fn.blank;

        return function (xhr) {
            var source = xhr.responseText,
                obj = 'string' == typeof source ? T.json.parse(source) : source;

            if (!obj || 'object' != typeof obj) {
                onerror({global : 'parse response error!!'});
                return;
            };

            if (!obj.status) {
                onsuccess(obj.data, obj);
            } else {
                switch( obj.status) {
                    case request.BUSINESS_ERROR : businessError(onerror, obj.statusInfo, obj);
                        break;
                    case request.SYSTEM_ERROR : systemError(obj.statusInfo || {}, obj);
                        break;
                    case request.NO_AUTH : gotoIndex();
                        break;
                    case request.NO_LOGIN : gotoLogin();
                        break;
                    default : unknowError();
                }

            }
        };

    }

    /**
     * 请求返回后回调函数
     */
    /**
     * get 
     */
    request.get = function (url, params, onsuccess, onerror) {
        T.ajax.request(url, {
            method : 'GET',
            data : params,
            onsuccess : getProcessHandler(onsuccess, onerror),
            onfailure : unknowError
        })
    };

    /**
     * post
     */
    request.post = function (url, params, onsuccess, onerror) {
        T.ajax.request(url, {
            method : 'POST',
            data : params,
            onsuccess : getProcessHandler(onsuccess, onerror),
            onfailure : unknowError
        });
    }
})(T, adbox);